import { Suspense, FC, useEffect } from "react";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import * as Type from "../utils/index";

type Props = {
  routes: Type.RouterList;
};

const BeforRouter = ({ Com , name }: { Com: any; name: any }) => {
    useEffect(()=>{
      document.title = name
    })
  return <Com></Com>;
}

const RouterView: FC<Props> = ({ routes }) => {
  const renderRoutes = (arr: Type.RouterList) => {
    return arr.map((item:Type.RouterItem, index:number) => {
      return (
        <Route
          key={index}
          path={item.path}
          element={
            item.to ? (
             <Navigate to={item.to}/>
            ) : (
             <BeforRouter Com={item.element} name={item.name as string}></BeforRouter>
            )
          }
        >
          {item.children && renderRoutes(item.children)}
        </Route>
      );
    });
  };
  return (

      <Suspense fallback={<>路由加载中</>}>
        <BrowserRouter>
          <Routes>{renderRoutes(routes)}</Routes>
        </BrowserRouter>
      </Suspense>

  );
};

export default RouterView;
